package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheCilent;
import com.hmdp.utils.SystemConstants;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheCilent cacheClient;

    @Override
    public Result queryId(Long id) {


        // 缓存穿透！
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,
//                    this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        // 互斥锁解决缓存击穿问题。
        Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿问题
      /*  Shop shop = cacheClient.queryWithExpireTime(CACHE_SHOP_KEY,id,Shop.class,
                this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);*/
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);

    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不存在");
        }

        updateById(shop);

        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //不需要根据坐标查询
        if(x==null ||y==null){
            Page<Shop> page = new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE);
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getTypeId,typeId);
            this.page(page,queryWrapper);
            return Result.ok(page.getRecords());
        }

        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = from + SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis，按照距离排序，分⻚，查询半径为5公⾥以内的商户。 结果为shopId - distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results =
                stringRedisTemplate.opsForGeo().search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(
                                end)
                );
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            return Result.ok(Collections.emptyList());
        }
        ArrayList<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());

        list.stream().skip(from).forEach(result -> {
            //获取店铺id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
            //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId,distance);
        });
        //根据id查询店铺（注意有序）
        String idListStr = StrUtil.join(",", ids);
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Shop::getId,ids).last("ORDER BY FIELD(id," + idListStr + ")");
        List<Shop> shopList = this.list(queryWrapper);
        //店铺与距离相映射

        shopList.forEach(shop->{
            Distance distance = distanceMap.get(shop.getId().toString());
            shop.setDistance(distance.getValue());
        });
        return Result.ok(shopList);

    }


    //获取锁
    public Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    public void unLock(String key) {
        Boolean flag = stringRedisTemplate.delete(key);
    }


/*    public Shop queryWithPassThrough(Long id){
        String CacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        if (StringUtils.isNotBlank(CacheShop)) {
            return JSONUtil.toBean(CacheShop, Shop.class);
        }

        if (CacheShop != null) {
            return null;
        }

        Shop shop = getById(id);

        if (shop == null) {
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }*/

    public Shop queryWithMutex(Long id){

        String CacheShop = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        if (StringUtils.isNotBlank(CacheShop)) {
            return JSONUtil.toBean(CacheShop, Shop.class);
        }

        if (CacheShop != null) {
            return null;
        }
        Shop shop = null;

        try {
            //获取互斥锁
            Boolean tryLock = tryLock("lock:shop:" + id);
            if (!tryLock) {
                Thread.sleep(20);
                return queryWithMutex(id);
            }

            shop = getById(id);

            if (shop == null) {
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock("lock:shop:" + id);
        }

        return shop;
    }
}




